package com.hadoop.mr.job;

import com.hadoop.mr.mapper.ClientCountMapper;
import com.hadoop.mr.reducer.ClientCountReducer;
import com.hadoop.mr.writable.ClientWritable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;

import java.io.IOException;

/**
 * Created by Administrator on 2019/7/11.
 */
public class ClientJob {
    public static Integer goodsId;

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        if (args == null || args.length < 1) {
            System.err.println("Parameter Errors! Usage <inputPath...> ");
            System.exit(-1);
        }
        String input = args[0];
        // 读取配置文件
        Configuration conf = new Configuration();
        DBConfiguration.configureDB(conf, "com.mysql.jdbc.Driver",
                "jdbc:mysql://192.168.31.43:3306/gator", "root", "tiger");

        Job job = Job.getInstance(conf, "clientCount");
        // 指定本类、mapper、reducer类
        job.setJarByClass(ClientJob.class);
        job.setMapperClass(ClientCountMapper.class);
        job.setReducerClass(ClientCountReducer.class);
        // 指定 mapper 输出 key 和 value 类
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(ClientWritable.class);
        // 指定 reducer 输出 key 和 value 类
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(ClientWritable.class);
        // 参数: 分析文件路径
        FileInputFormat.addInputPath(job, new Path(input));
        //设置格式DBOutputFormat
        job.setOutputFormatClass(DBOutputFormat.class);

        try {
            // 输出到哪些表、字段
            DBOutputFormat.setOutput(job, "client_count", "goods_name", "goods_type","client", "count");
            // 在 hadoop 中运行结果
            boolean flag = job.waitForCompletion(true);
            if (flag) {
                System.out.println("success");
            } else {
                System.out.println("error");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setGoodsId(Integer id) {
        if (goodsId == null || goodsId == 0) {
            goodsId = id;
        }
    }
}
